/*
 * @Author: tanjunyi@doctorwork.com
 * @Date: 2020-06-20 20:11:58
 * @LastEditors: tanjunyi@doctorwork.com
 * @LastEditTime: 2020-06-21 10:50:13
 * @Description:
 */
function genProps(attrs) {
	let str = '';
	let attObj = {}
	attrs.map(attr => {
		if (attr.name == 'style') {
			let obj = {}
			attr.value.split(';').forEach(item => {
				let [key, value] = item.split(':')
				obj[key] = value;
			})
			attr.value = obj; //将样式字符串换成了格式化后的对象
		}
		attObj[attr.name] = attr.value;
		// str += `${attr.name} :${JSON.stringify(attr.value)},`
	})
	// return `{${str.slice(0, -1)}}`
	return JSON.stringify(attObj)
}
var defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g;

function gen(node) {
	if (node.type === 1) {
		return generate(node)
	} else {
		// 文本的处理
		let text = node.text;
		if (!defaultTagRE.test(text)) {
			return `_v(${JSON.stringify(text)})` //
		} else {
			let tokens = [];
			let lastIndex = defaultTagRE.lastIndex = 0;
			let match, index;
			while (match = defaultTagRE.exec(text)) {
				index = match.index;
				tokens.push(JSON.stringify(text.slice(lastIndex, index)))
				tokens.push(`_s(${match[1].trim()})`)
				lastIndex = index + match[0].length
			}
			if (lastIndex < text.length) {
				tokens.push(JSON.stringify(text.slice(lastIndex)))
			}
			return `_v(${tokens.join('+')})`
		}
	}
}

function genChildren(el) {
	const children = el.children;
	if (children) {
		return children.map(c => gen(c)).join(',')
	} else {
		return false;
	}
}

export const generate = (el) => {
	let children = genChildren(el);
	let code = `_c("${el.tag}",${
		el.attrs.length ? `${genProps(el.attrs)}` : undefined
		},${children ? `${children}` : ''})`;
	return code;
}